package xin.ryven.car.android.ui

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.Window
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import xin.ryven.car.android.R
import xin.ryven.car.android.api.AuthApi
import xin.ryven.car.android.api.LoginRequest
import xin.ryven.car.android.api.SendVerificationCodeRequest
import xin.ryven.car.android.databinding.DialogLoginBinding
import xin.ryven.car.android.utils.TokenManager

class LoginDialog(
    context: Context,
    private val authApi: AuthApi,
    private val onLoginSuccess: () -> Unit
) : Dialog(context, R.style.TransparentDialog) {

    private lateinit var binding: DialogLoginBinding
    private var countDownTimer: CountDownTimer? = null
    private val coroutineScope = CoroutineScope(Dispatchers.Main + Job())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置对话框样式
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        
        binding = DialogLoginBinding.inflate(LayoutInflater.from(context))
        setContentView(binding.root)
        
        // 车机环境优化的对话框大小设置
        window?.let { window ->
            val layoutParams = window.attributes
            val displayMetrics = context.resources.displayMetrics
            
            // 获取屏幕尺寸
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            
            // 设置宽度：车机环境下使用较小比例，确保内容完整显示
            val targetWidth = (screenWidth * 0.45).toInt() // 从60%改为45%
            val minWidth = (400 * displayMetrics.density).toInt()
            val maxWidth = (700 * displayMetrics.density).toInt()
            
            layoutParams.width = targetWidth.coerceIn(minWidth, maxWidth)
            
            // 设置最大高度，确保按钮不被裁剪
            val maxHeight = (screenHeight * 0.8).toInt() // 最大高度为屏幕的80%
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
            layoutParams.flags = layoutParams.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
            
            // 确保对话框在屏幕中央
            layoutParams.gravity = android.view.Gravity.CENTER
            
            window.attributes = layoutParams
            
            // 设置软键盘模式，避免键盘遮挡按钮
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        }
        
        // 设置对话框可以取消
        setCancelable(true)
        setCanceledOnTouchOutside(true)

        setupClickListeners()
        setupAnimations()
    }
    
    private fun setupAnimations() {
        // 入场动画
        binding.root.alpha = 0f
        binding.root.scaleX = 0.7f
        binding.root.scaleY = 0.7f
        
        val fadeIn = ObjectAnimator.ofFloat(binding.root, "alpha", 0f, 1f)
        val scaleXIn = ObjectAnimator.ofFloat(binding.root, "scaleX", 0.7f, 1f)
        val scaleYIn = ObjectAnimator.ofFloat(binding.root, "scaleY", 0.7f, 1f)
        
        val animatorSet = AnimatorSet()
        animatorSet.playTogether(fadeIn, scaleXIn, scaleYIn)
        animatorSet.duration = 300
        animatorSet.interpolator = AccelerateDecelerateInterpolator()
        animatorSet.start()
    }

    private fun setupClickListeners() {
        binding.cancelButton.setOnClickListener {
            dismiss()
        }

        binding.getVerificationCodeButton.setOnClickListener {
            val phone = binding.phoneInput.text?.toString()
            if (phone.isNullOrEmpty() || phone.length != 11) {
                showErrorToast("请输入正确的手机号")
                shakeView(binding.phoneInput)
                return@setOnClickListener
            }

            // 禁用按钮并开始倒计时
            startCountDown()

            // 发送验证码请求
            coroutineScope.launch {
                try {
                    // 显示加载状态
                    binding.getVerificationCodeButton.text = "发送中..."
                    
                    val response = authApi.sendVerificationCode(SendVerificationCodeRequest(phone))
                    if (response.isSuccessful && response.body() != null) {
                        val verifyResponse = response.body()!!
                        if (verifyResponse.code == 0) {
                            showSuccessToast("验证码发送成功")
                        } else {
                            showErrorToast("发送失败: ${verifyResponse.msg}")
                            resetCountDown()
                        }
                    } else {
                        showErrorToast("发送验证码失败")
                        resetCountDown()
                    }
                } catch (e: Exception) {
                    showErrorToast("网络错误: ${e.message}")
                    resetCountDown()
                }
            }
        }

        binding.loginButton.setOnClickListener {
            val phone = binding.phoneInput.text?.toString()
            val code = binding.verificationCodeInput.text?.toString()

            if (phone.isNullOrEmpty() || code.isNullOrEmpty()) {
                showErrorToast("请输入手机号和验证码")
                if (phone.isNullOrEmpty()) shakeView(binding.phoneInput)
                if (code.isNullOrEmpty()) shakeView(binding.verificationCodeInput)
                return@setOnClickListener
            }

            // 显示登录加载状态
            binding.loginButton.isEnabled = false
            binding.loginButton.text = "登录中..."

            coroutineScope.launch {
                try {
                    val response = authApi.login(LoginRequest(phone, code))
                    println("response: $response")
                    if (response.isSuccessful && response.body() != null) {
                        val loginResponse = response.body()!!
                        if (loginResponse.code == 0) {
                            // 登录成功
                            TokenManager.saveToken(context, loginResponse.data.token)
                            showSuccessToast("登录成功")
                            
                            // 添加成功动画后关闭
                            animateSuccess {
                                dismiss()
                                onLoginSuccess()
                            }
                        } else {
                            // 登录失败，显示服务器返回的错误信息
                            showErrorToast("登录失败: ${loginResponse.msg}")
                            resetLoginButton()
                        }
                    } else {
                        showErrorToast("登录失败")
                        resetLoginButton()
                    }
                } catch (e: Exception) {
                    showErrorToast("网络错误: ${e.message}")
                    resetLoginButton()
                }
            }
        }
    }
    
    private fun shakeView(view: android.view.View) {
        val shake = ObjectAnimator.ofFloat(view, "translationX", 0f, 25f, -25f, 25f, -25f, 15f, -15f, 6f, -6f, 0f)
        shake.duration = 500
        shake.start()
    }
    
    private fun animateSuccess(onComplete: () -> Unit) {
        val scaleX = ObjectAnimator.ofFloat(binding.root, "scaleX", 1f, 1.1f, 0.8f)
        val scaleY = ObjectAnimator.ofFloat(binding.root, "scaleY", 1f, 1.1f, 0.8f)
        val alpha = ObjectAnimator.ofFloat(binding.root, "alpha", 1f, 0f)
        
        val animatorSet = AnimatorSet()
        animatorSet.playTogether(scaleX, scaleY, alpha)
        animatorSet.duration = 400
        animatorSet.start()
        
        animatorSet.addListener(object : android.animation.AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: android.animation.Animator) {
                onComplete()
            }
        })
    }
    
    private fun resetLoginButton() {
        binding.loginButton.isEnabled = true
        binding.loginButton.text = "登录"
    }
    
    private fun resetCountDown() {
        countDownTimer?.cancel()
        binding.getVerificationCodeButton.isEnabled = true
        binding.getVerificationCodeButton.text = "获取验证码"
    }

    private fun startCountDown() {
        binding.getVerificationCodeButton.isEnabled = false
        countDownTimer?.cancel()
        countDownTimer = object : CountDownTimer(60000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                binding.getVerificationCodeButton.text = "${millisUntilFinished / 1000}秒"
            }

            override fun onFinish() {
                binding.getVerificationCodeButton.isEnabled = true
                binding.getVerificationCodeButton.text = "获取验证码"
            }
        }.start()
    }
    
    private fun showSuccessToast(message: String) {
        Toast.makeText(context, "✅ $message", Toast.LENGTH_SHORT).show()
    }
    
    private fun showErrorToast(message: String) {
        Toast.makeText(context, "❌ $message", Toast.LENGTH_SHORT).show()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        countDownTimer?.cancel()
        coroutineScope.coroutineContext[Job]?.cancel()
    }
} 